<template>
  <div class="container">
    <topTitle
      :titleText="titleText"
      :back="back"
      @gobackTriser="goBack"
    ></topTitle>
    <div class="mainCon noTitleExplain">
      <el-form
        :model="formData"
        label-width="120px"
        :rules="formRules"
        ref="formData"
        class="form"
      >
        <el-row class="row-padding-bottom">
          <el-col :span="24" class="col-position">
            <el-form-item label="规则名称：" prop="ruleName">
              <el-input
                v-model="formData.ruleName"
                placeholder="请输入规则名称"
                @blur="formData.ruleName = changeValue($event)"
                class="dialogSingleInp"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row-padding-bottom">
          <el-col :span="18">
            <el-form-item label="打卡地址：" prop="address">
              <el-input
                v-model="formData.address"
                id="suggestId"
                class="dialogSingleInp"
              ></el-input>
              <div
                id="searchResultPanel"
                style="
                  border: 1px solid #c0c0c0;
                  width: 150px;
                  height: auto;
                  display: none;
                "
              ></div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row
          class="row-padding-bottom"
          style="margin: 0 0 22px 120px; width: 666px"
        >
          <el-col :span="24" class="col-position"
            >可在地图中通过移动标记点进行更精确定位</el-col
          >
          <el-col :span="24" class="col-position">
            <div id="l-map" style="height: 300px">地图</div>
          </el-col>
        </el-row>
        <el-row class="row-padding-bottom">
          <el-col :span="24">
            <el-form-item label="打卡范围：" prop="range">
              <el-select
                v-model="formData.range"
                filterable
                placeholder="请选择"
                class="dialogSingleInp"
              >
                <el-option
                  v-for="item in rangeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option> </el-select
              >&nbsp;&nbsp;&nbsp;&nbsp;员工可在范围内正常打卡
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row-padding-bottom" style="margin-top: 18px">
          <el-col :span="24" class="col-position">
            <el-form-item label>
              <el-button
                class="commonBut saveBtn"
                v-sdc
                @click="toSaveRule"
                :loading="isAdd"
                >保存</el-button
              >
              <el-button class="commonBut" v-sdc @click="goBack"
                >取消</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </div>
</template>
<script>
export default {
  name: 'constructAddPunchCardRule',
  data() {
    var checkLat = (rule, value, callback) => {
      var that = this
      var address = ''
      if (that.formData.address) {
        var address = that.formData.address.replace(/\s/g, '')
      }
      setTimeout(function () {
        if (
          !that.formData.lat ||
          !address ||
          (that.flag == false && !that.formData.lat)
        ) {
          that.flag = true
          return callback(new Error('请输入有效地址'))
        } else {
          callback()
        }
      }, 1000)
    }
    return {
      show: false,
      titleText: '',
      formData: {
        ruleName: '',
        range: 100,
        address: '',
        lat: '',
        lon: '',
      },
      //验证
      formRules: {
        ruleName: [
          {
            min: 1,
            max: 20,
            required: true,
            message: '请输入20字以内的规则名称',
            trigger: 'blur',
          },
        ],
        address: [
          {
            required: true,
            validator: checkLat,
            trigger: 'blur',
          },
        ],
        range: [
          {
            required: true,
            pattern: /^[\s\S]*.*[^\s][\s\S]*$/,
            message: '请输入打卡范围',
            trigger: 'change',
          },
        ],
      },
      defaultProps: {
        children: 'children',
        label: 'label',
      },
      choiceName: [],
      expandOnClick: false,
      projectId: '',
      back: true,
      flag: true,
      isAdd: false,
      rangeList: [
        {
          value: 50,
          label: '50米',
        },
        {
          value: 100,
          label: '100米',
        },
        {
          value: 200,
          label: '200米',
        },
        {
          value: 300,
          label: '300米',
        },
        {
          value: 500,
          label: '500米',
        },
        {
          value: 1000,
          label: '1000米',
        },
        {
          value: 2000,
          label: '2000米',
        },
        {
          value: 3000,
          label: '3000米',
        },
        {
          value: 5000,
          label: '5000米',
        },
      ],
      LocationPoint: '', //所在地址
    }
  },
  created() {
    this.id = this.$route.query.id
    this.type = this.$route.query.type
    this.projectId = this.$route.query.projectId
    if (this.type == 'edit') {
      this.titleText = '编辑打卡规则'
      this.formData.ruleName = this.$route.query.name
      this.getRuleList()
    } else {
      this.titleText = '添加打卡规则'
    }
  },
  mounted() {
    if (this.titleText == '添加打卡规则') {
      this.$nextTick(function () {
        this.getLocation()
      })
    }
  },
  methods: {
    toSaveRule() {
      this.isAdd = true
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.formData.address = $('#suggestId').val()
          this.saveRule()
        } else {
          this.isAdd = false
        }
      })
    },
    saveRule() {
      var data = {
        pointName: this.formData.ruleName,
        range: this.formData.range,
        lon: this.formData.lon,
        lat: this.formData.lat,
        address: this.formData.address,
        projectId: this.projectId,
      }
      var url = ''
      if (this.type == 'edit') {
        data.pointId = this.id
        url = 'api-att/cs/pointframe/expand/update'
      } else {
        url = 'api-att/cs/pointframe/expand/add'
      }
      this.axios({
        method: 'post',
        url: url,
        data: data,
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.isAdd = false
              var text = this.type == 'edit' ? '编辑成功' : '添加成功'
              this.$message({
                message: text,
                type: 'success',
              })
              this.$router.push({
                path: '/home/constructAttendance/constructPunchCardRuleList',
                name: 'constructPunchCardRuleList',
                query: {
                  projectId: this.projectId,
                },
              })
              this.$store.commit('CHANGE_SLIDER_NAME', {
                oldUrl:
                  '/home/constructAttendance/qyConstructAttendanceContainer',
                newUrl: this.$router.currentRoute.fullPath,
              })
            } else {
              this.$message({
                message: response.data.errorMsg,
                type: 'error',
              })
              this.isAdd = false
            }
          },
          (response) => {
            this.$message({
              message: '保存失败，请重试',
              type: 'error',
            })
            this.isAdd = false
          }
        )
        .catch((error) => {
          this.$message({
            message: '保存失败，请重试',
            type: 'error',
          })
          this.isAdd = false
        })
    },
    //获取之前的打卡规则
    getRuleList() {
      var data = {
        pointId: this.id,
      }
      this.axios({
        method: 'post',
        url: 'api-att/cs/pointframe/expand/detail',
        data: data,
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.formData.range = response.data.result.range
              this.formData.address = response.data.result.address
              this.formData.lat = response.data.result.lat
              this.formData.lon = response.data.result.lon
              this.$nextTick(function () {
                this.getLocation()
              })
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    goBack() {
      this.$router.push({
        path: '/home/constructAttendance/constructPunchCardRuleList',
        name: 'constructPunchCardRuleList',
        query: {
          projectId: this.projectId,
        },
      })
      this.$store.commit('GOBACK_NAME', {
        oldUrl: '/home/constructAttendance/qyConstructAttendanceContainer',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    getLocation() {
      var that = this
      var map = new BMap.Map('l-map')
      function myFun(result) {
        var cityName = result.name
        map.setCenter(cityName)
        that.LocationPoint = cityName
        that.initMap(that.type)
      }
      var myCity = new BMap.LocalCity()
      myCity.get(myFun)
    },
    initMap(type) {
      var that = this

      //是否隐藏下拉框标识
      var isHide = true

      function G(id) {
        return document.getElementById(id)
      }

      var map = new BMap.Map('l-map')

      // 编辑，将之前的经纬度设置为地图中心点

      if (type == 'edit') {
        var point = new BMap.Point(that.formData.lon, that.formData.lat)

        if (type == 'edit') {
          setTimeout(function () {
            $('#suggestId').val(that.formData.address)
            isHide = false
          }, 100)
        }

        openDragend(point)
      } else {
        // 添加,将当前ip获取到的区域设置为地图中心点
        var myGeo = new BMap.Geocoder()
        // 将地址解析结果显示在地图上,并调整地图视野
        myGeo.getPoint(
          that.LocationPoint,
          function (point) {
            if (point) {
              openDragend(point)
            } else {
              // alert("您选择地址没有解析到结果!");
            }
          },
          '北京市'
        )
      }
      function openDragend(point) {
        map.centerAndZoom(point, 16)
        var mk = new BMap.Marker(point)
        map.addOverlay(mk)
        map.panTo(point)
        // 初始化可拖拽
        mk.enableDragging()
        mk.addEventListener('dragend', function (e) {
          that.formData.lon = e.point.lng
          that.formData.lat = e.point.lat
          var myGeo = new BMap.Geocoder()
          // 根据坐标得到地址描述
          myGeo.getLocation(
            new BMap.Point(e.point.lng, e.point.lat),
            function (result) {
              if (result) {
                that.formData.address = result.address
                $('#suggestId').val(result.address)
                isHide = false
              }
            }
          )
        })
      }

      //增加滚轮放大缩小
      map.enableScrollWheelZoom(true)
      var ac = new BMap.Autocomplete({
        input: 'suggestId',
        location: map,
        onSearchComplete: function (data) {
          if (!isHide) {
            ac.hide()
            isHide = true
          }
        },
      }) //建立一个自动完成的对象

      ac.addEventListener('onhighlight', function (e) {
        //鼠标放在下拉列表上的事件
        var str = ''
        var _value = e.fromitem.value
        var value = ''
        if (e.fromitem.index > -1) {
          value =
            _value.province +
            _value.city +
            _value.district +
            _value.street +
            _value.business
        }
        str =
          'FromItem<br />index = ' + e.fromitem.index + '<br />value = ' + value

        value = ''
        if (e.toitem.index > -1) {
          _value = e.toitem.value
          value =
            _value.province +
            _value.city +
            _value.district +
            _value.street +
            _value.business
        }
        str +=
          '<br />ToItem<br />index = ' +
          e.toitem.index +
          '<br />value = ' +
          value
        G('searchResultPanel').innerHTML = str
      })

      var myValue
      ac.addEventListener('onconfirm', function (e) {
        var suggestVal = $('#suggestId').val()
        $('#suggestId').bind('input propertychange', function () {
          if (that.formData.address != suggestVal) {
            that.flag = false
            that.formData.lon = ''
            that.formData.lat = ''
          }
        })
        //鼠标点击下拉列表后的事件
        var _value = e.item.value

        myValue =
          _value.province +
          _value.city +
          _value.district +
          _value.street +
          _value.business
        G('searchResultPanel').innerHTML =
          'onconfirm<br />index = ' +
          e.item.index +
          '<br />myValue = ' +
          myValue
        setPlace()
      })

      function setPlace() {
        map.clearOverlays() //清除地图上所有覆盖物
        function myFun() {
          var pp = local.getResults().getPoi(0).point //获取第一个智能搜索的结果
          that.formData.lon = pp.lng
          that.formData.lat = pp.lat
          openDragend(pp)
        }
        var local = new BMap.LocalSearch(map, {
          //智能搜索
          onSearchComplete: myFun,
        })
        local.search(myValue)
      }
    },
  },
}
</script>

<style scoped lang="less">
.department {
  transform-origin: left;
  .icon {
    color: #009588;
    font-size: 14px;
    vertical-align: middle;
    float: left;
    margin-right: 5px;
  }
  .name {
    // float: left;
    transform-origin: left;
    display: inline-block;
    font-style: normal;
    width: 245px;
    overflow: hidden; /*超出的部分隐藏起来。*/
    white-space: nowrap; /*不显示的地方用省略号...代替*/
    text-overflow: ellipsis; /* 支持 IE */
  }
  .del {
    transform-origin: left;
  }
}

// .row-padding-bottom {
//     margin-bottom: 10px;
// }

.mainCon {
  height: calc(100% - 67px);
  overflow-y: auto;
  padding: 0;
  /deep/ .el-form {
    padding: 50px 60px;
    .el-input__inner {
      // width: 340px;
    }
  }
  .treeBox {
    width: 666px;
    // width: 200px;
    background: #f5f7fa;
    border: 1px solid #dee5f4;
    border-radius: 4px;
    padding: 12px 16px;
    .tree {
      padding: 22px;
      height: 235px;
      overflow: auto;
      border-right: 1px solid #dee5f4;
      .el-tree {
        background: #f5f7fa;
        /deep/ .el-tree-node__label {
          overflow: hidden;
          text-overflow: ellipsis; /* 超出部分显示省略号 */
          white-space: nowrap; /*规定段落中的文本不进行换行 */
        }
      }
    }
    .selectedDepartment {
      padding: 12px;
      margin-top: -12px;
      padding-right: 0;
      height: 235px;
      overflow: auto;
      p {
        font-size: 14px;
        line-height: 36px;
        color: #999;
        border-bottom: 1px solid #dee5f4;
      }
      .del {
        font-size: 14px;
        color: #0070f5;
        cursor: pointer;
      }
    }
  }

  .addressNameInfo {
    line-height: 28px;
    width: 666px;
    i {
      font-size: 18px;
      color: #009588;
      vertical-align: middle;
    }
    .range {
      color: #999;
    }
  }
}

#choiceNameBox li {
  line-height: 40px;
  height: 40px;
}

@media screen and (max-width: 1280px) {
  .mainCon .el-form {
    padding: 50px 20px;
  }

  .mainCon .treeBox {
    width: 630px;
  }

  .department .name {
    width: 220px;
  }

  #l-map {
    height: 200px !important;
  }
}

@media all and (min-width: 1360px) and (max-width: 1470px) {
  #l-map {
    height: 235px !important;
  }
}
</style>
